package task5.chat;

import task5.Util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

/**
 * 客户端发送消息类，每个客户端都有一条发送消息的通道
 */
public class ClientSend implements Runnable{
    // 定义输入输出流
    private BufferedReader bufferedReader;
    private DataOutputStream dataOutputStream;
    // 客户端名字
    private String name;
    // 判断线程是否正在运行
    private boolean isRunning = true;

    public ClientSend(Socket socket,String name) {
        try {
            // 读取控制台的内容
            bufferedReader = new BufferedReader(new InputStreamReader(System.in));
            // 向服务器发送数据
            dataOutputStream = new DataOutputStream(socket.getOutputStream());
            this.name = name;
            // 将客户端名字发送过去
            send(this.name);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 客户端向服务器发送消息
     * @param message 消息内容
     */
    private void send(String message) {
        try {
            if (message != null && !message.equals("") ){
                dataOutputStream.writeUTF(message);
                dataOutputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 若客户端出现异常，则关闭
            isRunning = false;
            Util.close(dataOutputStream,bufferedReader);
        }
    }

    /**
     * 从控制台读取消息
     * @return
     */
    private String getMessageFromConsole() {
        String message = "";
        try {
            message = bufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message;
    }

    @Override
    public void run() {
        while (isRunning){
            String message = getMessageFromConsole();
            send(message);
        }
    }

}
